package pri.zxx.webdemo.controllers;


import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Parameters;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import pri.zxx.webdemo.config.ExPrint;
import pri.zxx.webdemo.entity.vo.ResultData;
import pri.zxx.webdemo.utils.GsonUtil;
import pri.zxx.webdemo.utils.QRCodeUtil;

import javax.imageio.ImageIO;

import jakarta.servlet.http.HttpServletResponse;

import java.awt.image.BufferedImage;
import java.io.IOException;
import java.net.URLEncoder;

/**
 * 生成二维码
 *
 * @author zxx
 */
@Controller
@RequestMapping("/qrcode")
@Tag(name = "LEARN_DEMO-二维码接口")
@Slf4j
public class QRCodeController {

	@PostMapping(value = "/generate")
	@Operation(summary = "生成二维码")
	@Parameters(value = {
			@Parameter(name = "content", description = "二维码内容"),
			@Parameter(name = "download", description = "是否提供下载", example = "false")
	})
	public void generateQRCode4Product(String content, Boolean download, HttpServletResponse response) throws IOException {
		if (StringUtils.isEmpty(content)) {
			this.toResponse(response, "请求参数为空");
			return;
		}
		synchronized (this) {
			try {
				// logImagePath - logo 文件  needCompress 是否压缩
				BufferedImage qRecodeImag = QRCodeUtil.createImage(content, null, false);
				response.setHeader("Cache-Control", "no-store");
				// 不设置缓存
				response.setHeader("Pragma", "no-cache");
				response.setDateHeader("Expires", 0);
				response.setContentType("image/png");
				//提供下载打开
				if (download) {
					response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode("qr_code.png", "UTF-8"));//去掉这行设置header的代码，前端访问可以直接展示
				}
				//为了保证大图背景不变色，formatName必须为"png"
				ImageIO.write(qRecodeImag, "png", response.getOutputStream());
			} catch (Exception e) {
				String print = ExPrint.print(e);
				log.error("生成二维码异常-->> {}", print);
				this.toResponse(response, e.getMessage());
			}
		}
	}

	/**
	 * 返回错误结果
	 */
	private void toResponse(HttpServletResponse response, String dataStr) throws IOException {
		response.reset();
		response.setContentType("application/json");
		response.setCharacterEncoding("utf-8");
		response.getWriter().print(GsonUtil.toJson(ResultData.fail(dataStr)));
	}
}
